library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;


entity framedecoder is
	Port ( 	clk : in  STD_LOGIC;
			
			-- incoming
			usb_data_valid : in std_logic;
			usb_data : in unsigned(7 downto 0);
			
			-- outgoing
			module_data_valid : out std_logic;
			module_data : out unsigned(7 downto 0);
			to_module : out unsigned(7 downto 0)
		);		 
end framedecoder;

		

architecture Behavioral of framedecoder is
	

	signal state : unsigned(2 downto 0) := "000";
	
	signal seq_nr : unsigned(7 downto 0) := (others => '0');

	signal module_id : unsigned(7 downto 0) := (others => '0');
	signal nr_bytes : unsigned(7 downto 0) := (others => '0');
	
begin


	
	process (clk)
	begin
		if rising_edge(clk) then
		
			case state is 
			
				when "000" =>	-- idle -> preamble
					if usb_data_valid='1' and usb_data=254 then
						state <= "001";
					end if;
				
				when "001" =>	-- sequencenumber			--- toooodooooo
					if usb_data_valid='1' then
						if usb_data=seq_nr then
							state <= "010";
						else
							state <= "000";
						end if;
					end if;
				
				when "010" =>	-- module id
					if usb_data_valid='1' then
						module_id <= usb_data;
						state <= "011";
					end if;
					
				when "011" =>	-- # bytes
					if usb_data_valid='1' then
						nr_bytes <= usb_data;
						state <= "100";
					end if;
					
				when "100" =>	-- crc-receive
					if usb_data_valid='1' then
						state <= "101";
					end if;
				
				when "101" =>	-- crc-check				--- toooodooooo
					if 1=1 then
						state <= "110";
					end if;

				when "110" =>
					if usb_data_valid='1' then
						nr_bytes <= nr_bytes - 1;
						if nr_bytes=1 then 
							state <= "000";
						end if;
					end if;
					
				when others =>
					state <= "000";
				

			end case;
			
		end if;
	end process;
	
	
	module_data_valid <= '1' when state="110" and usb_data_valid='1' else '0';
	module_data <= usb_data;
	to_module <= module_id;
	

end Behavioral;





